import { FileUtil, getLogger, getNode, hvigor, HvigorNode, HvigorPlugin } from '@ohos/hvigor'
import { hapTasks, OhosAppContext, OhosHapContext, OhosPluginId } from '@ohos/hvigor-ohos-plugin'
import { hapPlugin } from '@hadss/hmrouter-plugin'
import path from 'path'
import fs from 'fs'
/**
 * Case编译插件
 * 用于自动处理Case模块的构建配置和依赖关系
 */
export function casePlugin(): HvigorPlugin {
  return {
    pluginId: 'casePlugin',
    context() {
      return {
        name: 'casePlugin'
      }
    },
    async apply(currentNode: HvigorNode): Promise<void> {
      const logger = getLogger('casePlugin')
      const hapContext = currentNode.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext
      if (!hapContext) {
        return
      }

      // 在节点评估完成后处理issue
      hvigor.nodesEvaluated(() => {
        hapContext.targets(target => {
          currentNode.registerTask({
            name: 'caseRun',
            run() {
              generateNavigationPage(currentNode, hapContext, logger)
            },
            postDependencies: [target.getTargetName() + '@PreBuild']
          })
        })
      })

      hvigor.buildFinished(() => {
        const homepagePath = `${hapContext.getModulePath()}/src/main/ets/pages/HomePage.ets`
        if (FileUtil.exist(homepagePath)) {
          fs.unlinkSync(homepagePath)
          logger.info('Deleted HomePage.ets')
        }
      })
    }
  }
}

/**
 * 生成导航页面
 */
function generateNavigationPage(currentNode: HvigorNode, hapContext: OhosHapContext, logger: any) {
  try {
    const appContext: OhosAppContext = currentNode.getParentNode()?.getContext(OhosPluginId.OHOS_APP_PLUGIN)
    const projectPath = appContext.getProjectPath()
    const buildJsonPath = path.join(projectPath, 'case.build.json')

    if (!FileUtil.exist(buildJsonPath)) {
      logger.warn('No case build configuration found')
      return
    }

    const buildConfig = JSON.parse(FileUtil.readFileSync(buildJsonPath).toString())
    if (!buildConfig.modules?.length) {
      return
    }

    // 读取每个模块的manifest配置并生成按钮代码
    const issueItems = buildConfig.modules.map(module => {
      const manifestPath = path.join(projectPath, module.srcPath, 'manifest.json')
      if (!FileUtil.exist(manifestPath)) {
        logger.warn(`No manifest.json found for module ${module.name}`)
        return null
      }

      const manifest = JSON.parse(FileUtil.readFileSync(manifestPath).toString())
      return {
        name: module.name,
        caseNO: manifest.caseNO,
        desc: manifest.desc,
        home: manifest.home
      }
    }).filter(Boolean)

    // 生成列表项代码
    const listItemsCode = issueItems
      .map(
        item => `      ListItem() {
        Column() {
          Row() {
            Column() {
              Text('Issue-${item.caseNO}')
                .fontSize(16)
                .fontWeight(FontWeight.Bold)
                .margin({ bottom: 4 })
              Text('${item.desc}')
                .fontSize(14)
                .opacity(0.6)
            }
            .alignItems(HorizontalAlign.Start)
            .layoutWeight(1)

            Button('查看详情')
              .onClick(() => {
                HMRouterMgr.push({ pageUrl: '${item.home}' });
              })
              .height(32)
              .fontSize(14)
          }
          .width('100%')
          .justifyContent(FlexAlign.SpaceBetween)
          .alignItems(VerticalAlign.Center)
        }
        .width('100%')
        .padding(16)
        .backgroundColor(Color.White)
        .borderRadius(8)
      }
      .margin({ bottom: 8 })`
      )
      .join('\n')

    // 生成页面内容
    const pageContent = `import { HMRouter, HMRouterMgr } from "@hadss/hmrouter";

@HMRouter({ pageUrl: 'homePage' })
@Component
export struct HomePage {
  build() {
    Column() {
      Text('Issue Demo 导航')
        .fontSize(20)
        .fontWeight(FontWeight.Bold)
        .margin({ top: 20, bottom: 16 })
      
      List() {
${listItemsCode}
      }
      .width('100%')
      .layoutWeight(1)
      .padding({ left: 16, right: 16 })
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#F5F5F5');
  }
}`

    const homepagePath = `${hapContext.getModulePath()}/src/main/ets/pages/HomePage.ets`
    FileUtil.ensureFileSync(homepagePath)
    FileUtil.writeFileSync(homepagePath, pageContent)
    logger.info('Generated HomePage.ets with navigation buttons')
  } catch (error) {
    logger.error(`Failed to generate navigation page: ${error}`)
  }
}

export default {
  system: hapTasks,
  plugins: [casePlugin(), hapPlugin()]
}
